"use strict";

var path = require('path'),
    C = require('../common'),
    _ = C._,
    S = C.S;

var fileBasedI18nFactory = function (basePath, lang) {
    return function (domain, text, values) {
        var path = basePath + lang + '/' + domain + '.js',
            langInfo, translated;

        try {
            langInfo = require(path);
        } catch (e) {
            C.H.syslog('warn', 'Missing language file: ' + path);
        }

        if (langInfo) {
            translated = langInfo[text];
            if (!translated) {
                C.H.syslog('warn', 'Missing translation: ' + path + ' -> ' + text);
                translated = text;
            }
        } else {
            translated = text;
        }

        return this.values ? S(translated).template(values).s : translated;
    };
};

var nonI18n = function (domain, text, values) {
    return values ? S(text).template(this.values).s : text;
};

var create = function (basePath, config) {
    if (!config) {
        return nonI18n;
    }

    C.excludeDotDotInPath('language locale', config.locale);

    config.storage || (config.storage = 'lang');

    if (_.isString(config.storage)) {
        var langPath = path.resolve(basePath, config.storage);
        langPath = C.ensureRightSlash(langPath);

        return fileBasedI18nFactory(langPath, config.locale);
    }

    //todo: add other storage factory
    return nonI18n;
};

module.exports = {

    type: 'init',

    load: function (owner, config, cb) {
        owner.__ = create(owner.root, config);

        cb();
    }
};